package com.citycloud.ccuap.tc.admin.project;

import com.citycloud.ccuap.commons.db.SqlRestrictions;
import com.citycloud.ccuap.commons.sys.entity.SysDeptment;
import com.citycloud.ccuap.commons.sys.entity.SysParameter;
import com.citycloud.ccuap.commons.sys.entity.SysProject;
import com.citycloud.ccuap.commons.sys.entity.SysProjectDeptmentRel;
import com.citycloud.ccuap.commons.sys.entity.SysProjectManager;
import com.citycloud.ccuap.commons.sys.entity.SysUser;
import com.citycloud.ccuap.commons.sys.entity.SysUserDeptRel;
import com.citycloud.ccuap.commons.sys.repository.SysDeptmentRepository;
import com.citycloud.ccuap.commons.sys.repository.SysParameterRepository;
import com.citycloud.ccuap.commons.sys.repository.SysProjectDeptmentRelRepository;
import com.citycloud.ccuap.commons.sys.repository.SysProjectManagerRepository;
import com.citycloud.ccuap.commons.sys.repository.SysUserDeptRelRepository;
import com.citycloud.ccuap.commons.sys.repository.SysUserRepository;
import com.citycloud.ccuap.framework.exception.AppAssert;
import com.citycloud.ccuap.framework.service.mybatis.MybatisServiceImpl;
import com.citycloud.ccuap.tc.admin.entity.SysProjectFunction;
import com.citycloud.ccuap.tc.admin.repository.SysProjectFunctionRepository;
import com.citycloud.ccuap.tc.admin.repository.SysYqProjectRepository;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 项目（站点）信息业务处理实现
 * @author zhusr
 *
 */
@Service("tcProjectService")
public class ProjectService extends MybatisServiceImpl<SysYqProjectRepository, SysProject, Long> implements IProjectService {

    @Autowired
    private SysProjectManagerRepository sysProjectManagerRepository;

    @Autowired
    private SysParameterRepository sysParameterRepository;

    @Autowired
    @Qualifier("sysYqProjectRepository")
    private SysYqProjectRepository sysYqProjectRepository;
    @Value("${tc.authorizationProjectId}")
    private Integer authorizationProjectId;

    @Autowired
    private SysProjectDeptmentRelRepository sysProjectDeptmentRelRepository;

    @Autowired
    private SysDeptmentRepository deptmentRepository;

    @Autowired
    private SysUserRepository sysUserRepository;

    @Autowired
    private SysUserDeptRelRepository sysUserDeptRelRepository;

    @Autowired
    private SysProjectFunctionRepository sysProjectFunctionRepository;

    @Override
    public void updateManagerInfo(ProjectUserDTO projectUserDTO) {
        if(null!=projectUserDTO){
            Long projectId=projectUserDTO.getProjectId();
            List<UserDTO> users=projectUserDTO.getUsers();
            List<Long> userIdList =new ArrayList<>();
            List<String> userNames=new ArrayList<>();
            if(!CollectionUtils.isEmpty(users)) {
                for (UserDTO user : users) {
                    userIdList.add(user.getUserId());
                    userNames.add(user.getUserName());
                }
            }
            SysProject sysProject = repository.findById(projectId).orElse(null);
            Assert.notNull(sysProject, "查询站点信息为空");
            sysProjectManagerRepository.deleteByProjectId(projectId);
            for (Long userId : userIdList) {
                SysProjectManager projectManager = new SysProjectManager();
                projectManager.setProjectId(projectId);
                projectManager.setManagerId(userId);
                sysProjectManagerRepository.save(projectManager);
            }
            sysProject.setManagerIds(StringUtils.join(userIdList.toArray(), ","));
            sysProject.setManagerNames(StringUtils.join(userNames.toArray(), ","));
            repository.save(sysProject);
        }

    }

    @Override
    public void deleteLogic(Long projectId) {
        SysProject sysProject = findById(projectId);
        AppAssert.isTrue(sysProject.getDataStatus() == 0, "站点启用状态不允许删除！");
        Assert.notNull(sysProject, "查询站点信息为空！");
        if(sysProject.getDataStatus()!= null && sysProject.getDataStatus().equals(String.valueOf(0))) {
            return;
        }
        Assert.isTrue(!validatePlatformSite(String.valueOf(projectId)),"平台级站点不可删除！");

        // 判断有无关联数据
        List<SysProjectDeptmentRel> deptmentRels = sysProjectDeptmentRelRepository.findByProjectId(projectId);
        List<SysDeptment> deptmentList = deptmentRepository.findByProjectId(projectId);
        AppAssert.isTrue(deptmentRels.isEmpty() && deptmentList.isEmpty(), "该站点下存在部门未删除！");

        List<SysUser> userList = sysUserRepository.findByProjectId(projectId);
        List<SysUserDeptRel>  userDeptRels = sysUserDeptRelRepository.findByProjectId(projectId);
        AppAssert.isTrue(userList.isEmpty() && userDeptRels.isEmpty(), "该站点下存在用户未删除！");

        List<SysProjectFunction> functionList = sysProjectFunctionRepository.findByProjectIdOrderByOrderNo(projectId);
        AppAssert.isTrue(functionList.isEmpty(), "该站点下存在菜单未删除！");

        super.deleteById(projectId);
    }


    @Override
    public List<Map<String, Object>> findUsersInfoById(Long projectId) {
        String sql = " select user.* from sys_project_manager manager, sys_user user where manager.manager_id=user.user_id ";
        sql += SqlRestrictions.eq("manager.project_id", projectId);
        return selectList(sql, true);
    }

    @Override
    public List<Map<String, Object>> findDataGroupInfoById(Long projectId) {
        String sql = " select dg.* from sys_project_dg_rel rel, sys_datagroup dg where rel.datagroup_id=dg.datagroup_id ";
        sql += SqlRestrictions.eq("rel.project_id", projectId);
        return selectList(sql, true);
    }

    /**
     * 获取站点下拉列表
     * @return
     */
    @Override
    public List<Map<String, Object>> getProjectTextId() {
        String sql = "SELECT sp.project_id as id,sp.project_name as text FROM sys_project as sp";
        return selectList(sql, true);
    }

    @Override
    public void modify(SysProject sysProject) {
        SysProject existSysProject = findById(sysProject.getProjectId());
        Assert.notNull(existSysProject,"该站点不存在！");
        if (!existSysProject.getProjectNo().equals(sysProject.getProjectNo())) {
            List<SysProject> noList = sysYqProjectRepository.findByProjectNo(sysProject.getProjectNo());
            Assert.isTrue(CollectionUtils.isEmpty(noList),"站点编码不能重复！");
        }
        if (!existSysProject.getProjectName().equals(sysProject.getProjectName())) {
            List<SysProject> noList = sysYqProjectRepository.findByProjectNameAndDataStatusIs(sysProject.getProjectName(),true);
            Assert.isTrue(CollectionUtils.isEmpty(noList),"站点名称不能重复！");
        }
        AppAssert.isTrue(!validatePlatformSite(String.valueOf(sysProject.getProjectId())),"平台级站点不可修改！");
        sysProject.setProjectNo(existSysProject.getProjectNo());
        update(sysProject);
    }

    private boolean validatePlatformSite(String projectId){
        List<SysParameter> parameters = sysParameterRepository.findByCodeValue(authorizationProjectId);
        if(CollectionUtils.isNotEmpty(parameters)){
            for(SysParameter parameter : parameters ){
                if(parameter.getCodeValue().contains(projectId)){
                    return true;
                }
            }
        }
        return false;
    }

    public List<Map<String,Object>> findSysProjectByProjectTypeId(String id){
        String sql = "SELECT sp.project_name as projectName FROM sys_project as sp where project_type_id = \""+id+"\"";
        return selectList(sql, true);
    }
}